<template>
  <div class="login-container">
    <div class="login-box">
      <div class="title">
        <h2>奖学金评定系统</h2>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" prefix-icon="el-icon-user" placeholder="用户名/工号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" placeholder="密码" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" class="login-button">登录</el-button>
        </el-form-item>
        <div class="register-link">
          <el-link type="primary" @click="goToRegister">注册导师账号</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        role: 'TEACHER' // 默认设置为导师角色
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          console.log('登录数据：', this.loginForm)
          this.$store.dispatch('login', this.loginForm)
            .then(() => {
              this.loading = false
              const token = window.sessionStorage.getItem('token')
              const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}')
              console.log('登录成功，跳转到首页。保存的token:', token)
              console.log('保存的用户信息:', userInfo)
              this.$router.push('/home')
            })
            .catch(error => {
              console.error('登录失败：', error)
              this.$message.error(error.message || '登录失败，请稍后重试')
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    goToRegister() {
      this.$router.push('/register')
    }
  }
}
</script>

<style scoped>
.login-container {
  height: 100%;
  width: 100%;
  background-color: #2d3a4b;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  width: 400px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 5px;
  box-shadow: 0 0 10px #ccc;
}

.title {
  text-align: center;
  margin-bottom: 30px;
}

.title h2 {
  font-weight: bold;
  color: #409EFF;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
}

.register-link {
  margin-top: 15px;
  text-align: center;
}
</style> 